import { defineStore } from 'pinia'
import { login, logout, checkLogin } from '@/api/login'
import { ElMessage } from 'element-plus'
import { useRouteStore } from './route'
import pinia from '@/main'
import router from '@/router'
import { getLocal, removeAllItem, setLocal } from '@/utils/storage'

export const useUserStore = defineStore('USER', {
  state: () => {
    return {
      userInfo: getLocal('__userInfo__', {}),
    }
  },
  actions: {
    loginFn(value) {
      login(value).then(({ data }) => {
        if (!data.code) {
          // 登录成功
          this.userInfo = data.data
          setLocal('__userInfo__', data.data)
          ElMessage.success(data.txt)

          // 获取侧边菜单路由了
          const routeStore = useRouteStore()
          routeStore.getMenuRouteFn()

          // 要配置完路由才能发生跳转
          router.push('/')
        } else {
          // 登录失败
          ElMessage.error(data.txt)
        }
      })
    },
    // 退出登录
    logoutFn() {
      logout().then(({ data }) => {
        if (!data.code) {
          // 清除本地存储(导入的 storage 里的函数)
          removeAllItem()

          // 清除 大菠萝 里的数据
          const allStore = [...pinia._s.values()]
          allStore.forEach((item) => {
            item.$reset()
          })

          ElMessage.success(data.txt)
          router.push('/login')
        } else ElMessage.error('请勿重复退出！')
      })
    },
    checkLoginFn() {
      return new Promise((res, rej) => {
        checkLogin().then(({ data }) => {
          if (!data.code) {
            this.userInfo = data.data
            setLocal('__userInfo__', data.data)
          }

          res(data.code)
        })
      })
    },
  },
})
